Chat Application Using Socket.io
Posted By : Hotam Singh | 28-Oct-2017
Hi All, Today I am going to make a simple chat application using socket.io in Node.JS.
Introduction: We’ll be using socket.io for this application so let’s understand what socket.io is?
Socket.io: socket.io is a real-time engine that is reliable and very fast. It’s very popular engine that is used for real-time event-based communication(i.e bidirectional communication between two clients in a browser) in node.js. So, let’s start with creating our first server and establishing socket connection on the server.
The Web Framework: Before we start developing our server, we need a framework. we‘ll be using express framework for this. Make sure express is installed. If not installed, you can easily install by following command:
$ npm install express
Or if you want to save dependencies you have installed, just run command with --save flag as:
$ npm install express --save
It will save express as dependency in package.json file.
Step 1:
Create a package.json file that describes your project. To create package.json, open terminal and simply go to project folder(In my case my project folder is socket-chat) and type the following command:
$ npm test
It will populate some basic options (i.e. name, version, description, main license etc) and you have to answer accordingly.
In my case, package.json look like:
Step 2: Create a server. Put the following code in a file(server.js):
When you run your server from terminal using following command:
$ node server.js
It will console the following message
Now go to browser and go to “http://localhost:3000/” , You will see Hello World
Step 3: Serving our html file. As now server is created now we need to render some html file where we will send/receive messages. So let’s modify root get request:
We will change it to the following:
After adding my index.html my server will look like:
Step 4: As now server is completed. Now I will integrate socket.io into our server. I’ll continue this part in the next blog.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Hotam Singh
Hotam has 1.5 years of experience in Node.JS. He has worked on Front End, JavaScript, Jquery, Backbone.JS, Database: MySQL, MongoDB. His hobbies are playing Sudoku/Puzzles and watching movies.